package com.ja.openchat.ui.contact;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityContactChooseBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.group.GroupSendActivity;
import com.ja.openchat.viewmodels.ContactChooseViewModel;
import com.ja.openchat.views.CustomEditText;
import com.ja.openchat.views.SideIndexBar;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.goldze.mvvmhabit.base.BaseActivity;

public class ContactChooseActivity extends BaseActivity<ActivityContactChooseBinding,ContactChooseViewModel> {

    public enum ContactChooseType {
        //创建群组
        ContactChooseType_CreateSuperGroup,
        //群组增加成员-从联系人列表增加
        ContactChooseType_Group_Add_Member,
        //群组移除成员-从现有群组成员移除
        ContactChooseType_Group_Delete_Member,
        //群组增加管理员-从现有群组成员提升-只有群组拥有者，即创建者，才有权限增加或者删除群组管理员
        ContactChooseType_Group_Add_Manager,
        //群组删除管理员-从现有群管理员降级
        ContactChooseType_Group_Delete_Manager,
        //群组@人
        ContactChooseType_Group_At_Someone,
        ContactChooseType_Group_Dm_At_Someone,
        ContactChooseType_CreateSecreat,
        //群发
        ContactChooseType_CreateGroupSend,
    }

    private ContactChooseAdapter contactChooseAdapter;
    private List<UserInfo> contactList = new ArrayList<>();
    private Map<Long, UserInfo> choosedDic = new HashMap<>();
    private Map<Long, UserInfo> disableChooseDic = new HashMap<>();
    private List<Section> sectionList = new ArrayList<>();

    //类型
    private ContactChooseType chooseType = ContactChooseType.ContactChooseType_CreateSuperGroup;
    //从联系人详情创建群组
    private long fromContactId;

    //会话id
    private long chatId;
    //超级群组id
    private long supergroup_id;
    //群组管理相关
    //群组增加成员-从联系人列表增加
    //群组移除成员-从现有群组成员移除(不包括自己和管理员)
    //群组增加管理员-从现有群组成员提升
    private List<GroupMemberInfo> group_membersList;
    //群组增加管理员-从现有群组成员提升
    //群组删除管理员-从现有群管理员降级
    private List<GroupMemberInfo> group_managersList;
    private boolean allSeleter = false;

    //新建超级群组
    public static void startWithCreateSuperGroup(Activity activity) {
        startWithCreateSuperGroup(activity, 0);
    }

    //从联系人设置页面新建群组
    public static void startWithCreateSuperGroup(Activity activity, long fromContactId) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("fromContactId", fromContactId);
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_CreateSuperGroup);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    //从消息页面新建群发
    public static void startWithCreateGroupSend(Activity activity,int requestCode) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_CreateGroupSend);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent,requestCode);
    }

    //选择at某个，interface回调
    public static void startWithAtSomeone(Activity activity, long chatId, long supergroup_id) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("chatId", chatId);
        intent.putExtra("supergroup_id", supergroup_id);
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_Group_At_Someone);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }
    public static void startWithDmAtSomeone(Activity activity, long chatId, long supergroup_id) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("chatId", chatId);
        intent.putExtra("supergroup_id", supergroup_id);
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_Group_Dm_At_Someone);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    //邀请成员
    public static void startWithInviteMember(Activity activity, long chatId, List<GroupMemberInfo> membersList) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("chatId", chatId);
        intent.putParcelableArrayListExtra("membersList", new ArrayList<>(membersList));
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_Group_Add_Member);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    //删除成员
    public static void startWithRemoveMember(Activity activity, long chatId, List<GroupMemberInfo> membersList, List<GroupMemberInfo> memberIsManagersList) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("chatId", chatId);
        intent.putParcelableArrayListExtra("membersList", new ArrayList<>(membersList));
        intent.putParcelableArrayListExtra("memberIsManagersList", new ArrayList<>(memberIsManagersList));
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_Group_Delete_Member);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    //增加管理员
    public static void startWithAddManager(Activity activity, long chatId, List<GroupMemberInfo> membersList, List<GroupMemberInfo> memberIsManagersList) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("chatId", chatId);
        intent.putParcelableArrayListExtra("membersList", new ArrayList<>(membersList));
        intent.putParcelableArrayListExtra("memberIsManagersList", new ArrayList<>(memberIsManagersList));
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_Group_Add_Manager);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    //删除管理员
    public static void startWithRemoveManager(Activity activity, long chatId, List<GroupMemberInfo> memberIsManagersList) {
        Intent intent = new Intent();
        intent.setClass(activity, ContactChooseActivity.class);
        intent.putExtra("chatId", chatId);
        intent.putParcelableArrayListExtra("memberIsManagersList", new ArrayList<>(memberIsManagersList));
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", ContactChooseType.ContactChooseType_Group_Delete_Manager);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }


    public static void start(Context context, ContactChooseType type) {
        Intent intent = new Intent(context,ContactChooseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", type);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_contact_choose;
    }


    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ContactChooseViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ContactChooseViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        //初始化数据
        initIntentData();
        //初始化标题
        initTitle();
        //初始化导航栏
        initToolbar();
        //初始化列表
        initListView();
        //加载数据
        loadData();
        binding.toolbar.tvOkRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                click_ok();
            }
        });
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.larSeleter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                allSeleter = !allSeleter;
                binding.checkView.setSelected(allSeleter);
                if(allSeleter){
                    for (int i=0;i<sectionList.size();i++){
                        Object obj = sectionList.get(i).getObject();
                        if (obj instanceof UserInfo) {
                            UserInfo user = (UserInfo) obj;
                            choosedDic.put(user.id, user);
                        }
                    }
                }else {
                    choosedDic.clear();
                }
                contactChooseAdapter.notifyDataSetChanged();
            }
        });
        //索引事件
        binding.slide.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        binding.recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
        //点击事件
        contactChooseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        if (disableChooseDic.get(user.id) == null) {//不在不可更改的列表里
                            if (chooseType == ContactChooseType.ContactChooseType_Group_At_Someone) {//单选
                                finish();
                                EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Chat_At_Someone, user, chatId));
                            } else if (chooseType == ContactChooseType.ContactChooseType_Group_Dm_At_Someone) {//单选
                                finish();
                                EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Chat_Dm_At_Someone, user, chatId));
                            } else {//多选
                                if(chooseType == ContactChooseType.ContactChooseType_CreateSecreat){
                                    choosedDic.clear();
                                    choosedDic.put(user.id, user);
                                }else{
                                    if (choosedDic.get(user.id) != null) {
                                        choosedDic.remove(user.id);
                                    } else {
                                        choosedDic.put(user.id, user);
                                    }
                                }
                                //刷新多选按钮状态
                                freshAllSelStyle();
                                contactChooseAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
            }
        });
        contactChooseAdapter.setOnChooseListener(new ContactChooseAdapter.OnChooseListener() {
            @Override
            public boolean isSignalMode() {
                return chooseType == ContactChooseType.ContactChooseType_Group_At_Someone||chooseType == ContactChooseType.ContactChooseType_Group_Dm_At_Someone;
            }

            @Override
            public boolean isChoose(UserInfo user) {
                if (chooseType == ContactChooseType.ContactChooseType_Group_At_Someone||chooseType == ContactChooseType.ContactChooseType_Group_Dm_At_Someone) {//单选
                    return false;
                } else {//多选
                    return choosedDic.get(user.id) != null;
                }
            }

            @Override
            public boolean showMask(UserInfo user) {
                if (chooseType == ContactChooseType.ContactChooseType_Group_At_Someone||chooseType == ContactChooseType.ContactChooseType_Group_Dm_At_Someone) {//单选
                    return disableChooseDic.get(user.id) != null;
                } else {//多选
                    return disableChooseDic.get(user.id) != null;
                }
            }
        });
        //输入框监听
        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });

    }

    private void freshAllSelStyle(){
        boolean allSel = true;
        for (int i=0;i<sectionList.size();i++){
            Object obj = sectionList.get(i).getObject();
            if (obj instanceof UserInfo) {
                UserInfo user = (UserInfo) obj;
                if (choosedDic.get(user.id) == null) {//没有
                    allSel = false;
                }
            }
        }
        allSeleter = allSel;
        binding.checkView.setSelected(allSeleter);
    }

    private void initIntentData() {
        if (getIntent() != null) {
            chatId = getIntent().getLongExtra("chatId", 0);
            fromContactId = getIntent().getLongExtra("fromContactId", 0);
            supergroup_id = getIntent().getLongExtra("supergroup_id", 0);
            group_membersList = getIntent().getParcelableArrayListExtra("membersList");
            if (group_membersList == null) {
                group_membersList = new ArrayList<>();
            }
            group_managersList = getIntent().getParcelableArrayListExtra("memberIsManagersList");
            if (group_managersList == null) {
                group_managersList = new ArrayList<>();
            }
            //类型
            Bundle bundle = getIntent().getExtras();
            chooseType = (ContactChooseType) bundle.getSerializable("type");
            if (chooseType == null) {
                chooseType = ContactChooseType.ContactChooseType_CreateSuperGroup;
            }
        }
    }

    private void initTitle() {
        switch (chooseType) {
            case ContactChooseType_CreateSuperGroup:
                setTitle(fromContactId != 0 ? getString(R.string.select_friend) : getString(R.string.create_group));
                break;
            case ContactChooseType_Group_Add_Member:
                setTitle(getString(R.string.add_group_members));
                break;
            case ContactChooseType_Group_Add_Manager:
                setTitle(getString(R.string.add_group_administrator));
                break;
            case ContactChooseType_Group_Delete_Member:
                setTitle(getString(R.string.remove_group_members));
                break;
            case ContactChooseType_Group_Delete_Manager:
                setTitle(getString(R.string.remove_group_admin));
                break;
            case ContactChooseType_Group_At_Someone:
                setTitle(getString(R.string.choose_who_remind));
                break;
            case ContactChooseType_Group_Dm_At_Someone:
                setTitle(getString(R.string.choose_who_dm));
                break;
            case ContactChooseType_CreateSecreat:
                setTitle(getString(R.string.create_prive_chat));
                break;
            case ContactChooseType_CreateGroupSend:
                setTitle(getString(R.string.new_group_send));
                break;
            default:
                setTitle("");
                break;
        }
    }

    public void setTitle(String title) {
        TextView titleText = findViewById(R.id.tv_bar_title);
        if (titleText != null) {
            titleText.setText(title);
        }
    }

    private void initToolbar() {
        if(chooseType == ContactChooseType.ContactChooseType_CreateGroupSend){
            binding.larSeleter.setVisibility(View.VISIBLE);
        }else{
            binding.larSeleter.setVisibility(View.GONE);
        }
        switch (chooseType) {
            case ContactChooseType_CreateSuperGroup:
            case ContactChooseType_CreateGroupSend:
                binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
                binding.toolbar.tvOkRight.setText(fromContactId != 0 ? getString(R.string.finish_text) : getString(R.string.create_text));
                break;
            case ContactChooseType_Group_Add_Member:
            case ContactChooseType_Group_Add_Manager:
            case ContactChooseType_Group_Delete_Member:
            case ContactChooseType_Group_Delete_Manager:
                binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
                binding.toolbar.tvOkRight.setText(getString(R.string.finish_text));
                break;
            case ContactChooseType_Group_At_Someone:
            case ContactChooseType_Group_Dm_At_Someone:
                break;
            case ContactChooseType_CreateSecreat:
                binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
                binding.toolbar.tvOkRight.setText(getString(R.string.create_text));
                break;
            default:
                break;
        }
    }

    private void initListView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        contactChooseAdapter = new ContactChooseAdapter(chooseType == ContactChooseType.ContactChooseType_Group_At_Someone ||chooseType == ContactChooseType.ContactChooseType_Group_Dm_At_Someone?
                R.layout.adapter_contact_list : R.layout.adapter_choose_contact_list, R.layout.adapter_section_contact_list, sectionList);
        binding.recyclerView.setAdapter(contactChooseAdapter);
        viewModel.setAdapter(contactChooseAdapter);
    }

    private void loadData() {
        contactList.clear();
        switch (chooseType) {
            case ContactChooseType_CreateGroupSend:
            case ContactChooseType_CreateSuperGroup:
            case ContactChooseType_CreateSecreat:{//创建群组
                //不可更改部分
                if (fromContactId != 0) {
                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(fromContactId);
                    if (user != null) {
                        choosedDic.put(user.id, user);
                        disableChooseDic.put(user.id, user);
                    }
                }
                List<UserInfo> userInfos = TelegramManager.getTelegramManager().getTgData().getMyContacts();
                if(userInfos!=null&&userInfos.size()>0){
                    if(fromContactId==0){
                        for(UserInfo userInfo:userInfos){
                            if(userInfo.id!=UserInfo.getUserInfo().id){
                                contactList.add(userInfo);
                            }
                        }
                    }else{
                        contactList.addAll(userInfos);
                    }
                }
                //联系人列表

                reloadContacts(contactList);
            }
            break;
            case ContactChooseType_Group_Add_Member: {//增加群成员
                //不可更改部分
                for (GroupMemberInfo member : group_membersList) {
                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                    if (user != null) {
                        choosedDic.put(user.id, user);
                        disableChooseDic.put(user.id, user);
                    }
                }
                //联系人列表
                contactList.addAll(TelegramManager.getTelegramManager().getTgData().getMyContacts());
                reloadContacts(contactList);
            }
            break;
            case ContactChooseType_Group_Add_Manager: {//增加群管理员
                //不可更改部分
                for (GroupMemberInfo member : group_managersList) {
                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                    if (user != null) {
                        choosedDic.put(user.id, user);
                        disableChooseDic.put(user.id, user);
                    }
                }
                //联系人列表
                if (group_membersList.size() > 0) {
                    for (GroupMemberInfo member : group_membersList) {
                        UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                        if (user != null) {
                            contactList.add(user);
                        }
                    }
                }
                reloadContacts(contactList);
            }
            break;
            case ContactChooseType_Group_Delete_Member: {//删除群成员
                //不可更改部分-去除自己
                UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(UserInfo.getUserInfo().id);
                if (user != null) {
                    choosedDic.put(user.id, user);
                    disableChooseDic.put(user.id, user);
                }
                //不可更改部分-去除管理员
                for (GroupMemberInfo member : group_managersList) {
                    user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                    if (user != null) {
                        choosedDic.put(user.id, user);
                        disableChooseDic.put(user.id, user);
                    }
                }
                //联系人列表
                if (group_membersList.size() > 0) {
                    for (GroupMemberInfo member : group_membersList) {
                        user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                        if (user != null) {
                            contactList.add(user);
                        }
                    }
                }
                reloadContacts(contactList);
            }
            break;
            case ContactChooseType_Group_Delete_Manager: {//删除群管理员
                //不可更改部分-去除自己
                UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(UserInfo.getUserInfo().id);
                if (user != null) {
                    choosedDic.put(user.id, user);
                    disableChooseDic.put(user.id, user);
                }
                //联系人列表
                if (group_managersList.size() > 0) {
                    for (GroupMemberInfo member : group_managersList) {
                        user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                        if (user != null) {
                            contactList.add(user);
                        }
                    }
                }
                reloadContacts(contactList);
            }
            break;
            case ContactChooseType_Group_At_Someone:
            case ContactChooseType_Group_Dm_At_Someone:{//@某人
                TelegramManager.getTelegramManager().getSuperGroupMembers(this,chatId, supergroup_id, "supergroupMembersFilterRecent", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                        if (obj != null) {
                            group_membersList.addAll(obj);
                            //不可更改部分-去除自己
//                            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(UserInfo.getUserInfo().id);
//                            if (user != null) {
//                                choosedDic.put(user.id, user);
//                                disableChooseDic.put(user.id, user);
//                            }
                            //联系人列表
                            if (group_membersList.size() > 0) {
                                for (GroupMemberInfo member : group_membersList) {
                                    contactChooseAdapter.putGroupNickname(member.user_id,member.nickname);
                                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                                    if (user != null&&user.id != UserInfo.getUserInfo().id) {
                                        contactList.add(user);
                                    }
                                }
                            }
                            reloadContacts(contactList);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {

                    }
                });
            }
            break;
        }
    }

    private void doSearch(String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            List<UserInfo> list = new ArrayList<>();
            for (UserInfo user : contactList) {
                if (user.isMatch(keyword)) {
                    list.add(user);
                }
            }
            reloadContacts(list);
        } else {
            reloadContacts(contactList);
        }
    }

    private void reloadContacts(List<UserInfo> list) {
        sectionList.clear();
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        //生成a-z hash
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }
        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    sectionList.add(new Section(false, user));
                }
            }
        }
        //刷新页面
        contactChooseAdapter.notifyDataSetChanged();
    }

    private void createGroup() {
        if (choosedDic.size() < 2) {
            showErrorTip(getString(R.string.create_group_condition));
            return;
        }
        List<UserInfo> list = new ArrayList<>(choosedDic.values());
        Collections.sort(list, new Comparator<UserInfo>() {
            @Override
            public int compare(UserInfo u1, UserInfo u2) {
                if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                    return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                }
                return 0;
            }
        });
        //创建群组
        showProgress();
        TelegramManager.getTelegramManager().createSuperGroupChat(this, list, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {
                    finish();
                    ChatActivity.startActivity(ContactChooseActivity.this, (ChatInfo) obj.data);
                } else {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void createGroupSend() {
        if (choosedDic.size() < 2) {
            showErrorTip(getString(R.string.create_group_condition));
            return;
        }
        Set<Map.Entry<Long,UserInfo>> choosedSets = choosedDic.entrySet();
        ArrayList<Long> userIds = new ArrayList<>();
        for(Map.Entry<Long,UserInfo> entry:choosedSets){
            TelegramManager.getTelegramManager().createPrivateChat(this,entry.getValue().id,null);
            userIds.add(entry.getValue().id);
        }
        ChatActivity.startActivity(this,new GroupSendInfo(userIds), GroupSendActivity.REQUEST_CODE_FOR_GROUP_SEND);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == GroupSendActivity.REQUEST_CODE_FOR_GROUP_SEND){
            if(data!=null){
                setResult(Activity.RESULT_OK,data);
            }
            finish();
        }
    }

    private List<Long> filterChooseList() {
        List<UserInfo> list = new ArrayList<>(choosedDic.values());
        if (list.size() <= 0) {
            return new ArrayList<>();
        }
        List<Long> filterList = new ArrayList<>();
        for (UserInfo user : list) {
            if (disableChooseDic.get(user.id) == null) {
                filterList.add(user.id);
            }
        }
        return filterList;
    }

    private void addSuperGroupMembers() {
        List<Long> ids = filterChooseList();
        if (ids.size() <= 0) {
            showErrorTip(getString(R.string.please_select_friend));
            return;
        }
        //创建群组
        showProgress();
        TelegramManager.getTelegramManager().addMembers2SuperGroup(this, chatId, ids, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {
                    showErrorTip(getString(R.string.members_have_added));
                    finish();
                } else {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void addSuperGroupManager() {
        List<Long> ids = filterChooseList();
        if (ids.size() <= 0) {
            showErrorTip(getString(R.string.select_members));
            return;
        }
        //一个一个添加
        showProgress();
        addSuperGroupManager(ids, 0);
    }

    private void addSuperGroupManager(List<Long> ids, int index) {
        if (ids.size() <= 0 || ids.size() <= index) {//已执行完
            hideProgress();
            showErrorTip(getString(R.string.admin_has_added));
            finish();
            return;
        }
        long id = ids.get(index);
        int new_index = index + 1;
        TelegramManager.getTelegramManager().addManager2Group(this, chatId, id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {//下一个
                    addSuperGroupManager(ids, new_index);
                } else {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void deleteGroupMember() {
        List<Long> ids = filterChooseList();
        if (ids.size() <= 0) {
            showErrorTip(getString(R.string.select_members));
            return;
        }
        //一个一个移除
        showProgress();
        deleteGroupMember(ids, 0);
    }

    private void deleteGroupMember(List<Long> ids, int index) {
        if (ids.size() <= 0 || ids.size() <= index) {//已执行完
            hideProgress();
            showErrorTip(getString(R.string.member_removed));
            finish();
            return;
        }
        long id = ids.get(index);
        int new_index = index + 1;
        TelegramManager.getTelegramManager().removeMemberFromGroup(this, chatId, id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {//下一个
                    deleteGroupMember(ids, new_index);
                } else {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void deleteGroupManager() {
        List<Long> ids = filterChooseList();
        if (ids.size() <= 0) {
            showErrorTip(getString(R.string.select_group_manager));
            return;
        }
        //一个一个移除
        showProgress();
        deleteGroupManager(ids, 0);
    }

    private void deleteGroupManager(List<Long> ids, int index) {
        //超级群组管理员只有一个一个移除-先禁言再设置为普通成员
        if (ids.size() <= 0 || ids.size() <= index) {//已执行完
            hideProgress();
            showErrorTip(getString(R.string.group_admin_removed));
            finish();
            return;
        }
        long id = ids.get(index);
        int new_index = index + 1;
        TelegramManager.getTelegramManager().banMemberFromSuperGroup(this, chatId, id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {
                    toSuperGroupMember(ids, new_index, id);
                } else {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void toSuperGroupMember(List<Long> ids, int index, long memberId) {
        TelegramManager.getTelegramManager().removeManagerFromGroup(this, chatId, memberId, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {//下一个
                    deleteGroupManager(ids, index);
                } else {
                    showErrorTip(getString(R.string.request_error)  + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error) );
            }
        });
    }

    private void click_ok() {
        switch (chooseType) {
            case ContactChooseType_CreateSuperGroup:
                createGroup();
                break;
            case ContactChooseType_Group_Add_Member:
                addSuperGroupMembers();
                break;
            case ContactChooseType_Group_Add_Manager:
                addSuperGroupManager();
                break;
            case ContactChooseType_Group_Delete_Member:
                deleteGroupMember();
                break;
            case ContactChooseType_Group_Delete_Manager:
                deleteGroupManager();
                break;
            case ContactChooseType_Group_At_Someone:
                break;
            case ContactChooseType_CreateSecreat:
            case ContactChooseType_Group_Dm_At_Someone:
                creatNewSecretChat();
                break;
            case ContactChooseType_CreateGroupSend:
                createGroupSend();
                break;
            default:
                break;
        }
    }

    private void creatNewSecretChat(){
        if (choosedDic.isEmpty()) {
            showWarnTip(getString(R.string.select_friend));
            return;
        }
        Map.Entry<Long,UserInfo> entry = choosedDic.entrySet().iterator().next();
        showProgress();
        TelegramManager.getTelegramManager().createNewSecretChat(this, entry.getKey(), new TgResultBlock<ChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                hideProgress();
                if (obj!=null) {
                    ChatActivity.startActivity(ContactChooseActivity.this, obj);
                    finish();
                } else {
                    showErrorTip(getString(R.string.request_error) );
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error) );
            }
        });
    }

}